<template>
    <LayoutWrap class="permission">
        <el-form @submit.native.prevent ref="formSearch" :inline="true" :model="formSearch" label-width="80px">
            <div class="search-wrap">
                <div class="search-item" :class="{left: !isMobile}">
                    <el-form-item label="关键词" prop="keyName">
                        <el-select
                            class="custom-the-select_key"
                            popper-class="custom-the-select-popper_key"
                            v-model="formSearch.keyName"
                            placeholder="请选择"
                            style="width: 105px;margin-right: 10px;"
                        >
                            <el-option
                                v-for="item in keyOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                                :disabled="item.disabled"
                            >
                            </el-option>
                        </el-select>
                        <br v-if="isMobile" />
                        <el-input
                            v-model="formSearch.keyValue"
                            placeholder="请输入关键字检索"
                            @keyup.enter.native="getList"
                            style="width: 180px"
                        ></el-input>
                    </el-form-item>
                </div>
            </div>
            <div class="search-wrap">
                <div class="search-item" :class="{left: !isMobile}">
                    <el-form-item label="  ">
                        <el-button type="primary" style="min-width: 120px;" @click="getList">查询</el-button>
                        <br v-if="isMobile" />
                        <el-button type="default" style="min-width: 120px;" @click="resetForm('formSearch')"
                            >重置</el-button
                        >
                    </el-form-item>
                </div>
            </div>
        </el-form>
        <ul class="list-head">
            <li class="list-head-item">
                <el-button style="min-width:80px;" @click="onClickDetail(dataSourceDefault, '添加')" type="primary"
                    >添加</el-button
                >
            </li>
            <li class="list-head-item">
                <el-button
                    style="min-width:80px;"
                    @click="
                        multipleAddVisible = true;
                        multipleCreateSelection = [
                            {...dataSourceDefault, uuid: uuidv4()},
                            {...dataSourceDefault, uuid: uuidv4()}
                        ];
                    "
                    type="primary"
                    >批量添加</el-button
                >
            </li>
            <li class="list-head-item">
                <el-button
                    style="min-width:80px;"
                    :disabled="!isMultSelect"
                    @click="multipleUpdateVisible = true"
                    type="primary"
                    >批量修改</el-button
                >
            </li>
            <li class="list-head-item">
                <el-button
                    style="min-width:80px;"
                    :disabled="!isMultSelect"
                    @click="multipleDeleteVisible = true"
                    type="danger"
                    >批量删除</el-button
                >
            </li>
            <li class="list-head-item">
                <el-button
                    style="min-width:80px;"
                    :disabled="!isMultSelect"
                    @click="multipleDetailVisible = true"
                    type="danger"
                    >批量查看</el-button
                >
            </li>
        </ul>

        <el-table
            v-loading="isLoading"
            :data="tableData"
            border
            style="width: 100%"
            @selection-change="handleSelectionChange"
            ref="multipleUpdateTable"
        >
            <el-table-column type="selection" width="55"> </el-table-column>
            <el-table-column type="index" :index="indexMethod"> </el-table-column>
            <el-table-column prop="name" label="名称"> </el-table-column>
            <el-table-column prop="contact" label="联系人"> </el-table-column>
            <el-table-column prop="phone" label="联系电话"> </el-table-column>
            <el-table-column prop="address" label="地址"> </el-table-column>
            <el-table-column prop="outStart" label="期初应付"> </el-table-column>
            <el-table-column prop="outEnd" label="期末应付"> </el-table-column>
            <el-table-column prop="remark" label="备注"> </el-table-column>
            <el-table-column prop="date" label="创建时间">
                <template v-slot="{row}">
                    {{ row.date | formatDateFillStr }}
                </template>
            </el-table-column>
            <el-table-column prop="operator" label="操作人">
                <template v-slot="{row}">{{ row.operator && row.operator.name }}</template>
            </el-table-column>
            <el-table-column prop="operatorDate" label="操作时间">
                <template v-slot="{row}">
                    {{ row.operatorDate | formatDateFillStr }}
                </template>
            </el-table-column>
            <el-table-column align="center" label="操作">
                <template v-slot="{row}">
                    <el-button :disabled="isMultSelect" @click="onClickDetail(row, '编辑客户')" type="text">
                        编辑
                    </el-button>
                    <el-button :disabled="isMultSelect" @click="onClickDelete(row)" type="text">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <Pagination
            :page-size.sync="formSearch.pageSize"
            :page.sync="formSearch.page"
            :total="formSearch.count"
            @change="onChangePage"
        />
        <FunctionDialog
            :title="title"
            @on-ok="getList"
            :visible.sync="visibleDetail"
            :data-source="dataSourceDetail"
        ></FunctionDialog>
        <TheElDialog title="删除客户" :visible.sync="dialogVisible">
            <span>你确定删除 {{ dataSourceDetail.name }} 吗？</span>
            <span slot="footer" class="dialog-footer">
                <el-button :disabled="dialogLoading" @click="dialogVisible = false">取 消</el-button>
                <el-button :loading="dialogLoading" type="primary" @click="onClickOkDelete(dataSourceDetail)"
                    >确 定</el-button
                >
            </span>
        </TheElDialog>
        <BatchDialog
            type="add"
            title="批量添加客户"
            :visible.sync="multipleAddVisible"
            :isLoading.sync="isMultipleLoading"
            @on-ok="getList"
        ></BatchDialog>
        <BatchDialog
            type="edit"
            title="批量修改客户"
            :visible.sync="multipleUpdateVisible"
            :isLoading.sync="isMultipleLoading"
            :multipleSelection.sync="multipleSelection"
            :multipleValueSelection.sync="multipleValueSelection"
            :tableData="tableData"
            :onRemoveUpdateSelection="onRemoveUpdateSelection"
            @closed="handleSelectionChange(multipleValueSelection)"
            @on-ok="getList"
        ></BatchDialog>
        <BatchDialog
            type="detail"
            title="批量查看客户"
            :visible.sync="multipleDetailVisible"
            :isLoading.sync="isMultipleLoading"
            :multipleSelection.sync="multipleSelection"
        ></BatchDialog>
        <TheElDialog
            title="批量删除"
            :visible.sync="multipleDeleteVisible"
            minWidth
            @closed="handleSelectionChange(multipleValueSelection)"
        >
            <span>你确定删除下面客户吗？</span>
            <el-table v-loading="isMultipleLoading" :data="multipleSelection" :border="false" style="width: 100%">
                <el-table-column prop="name" label="名称"> </el-table-column>
                <el-table-column prop="contact" label="联系人"> </el-table-column>
                <el-table-column prop="phone" label="联系电话"> </el-table-column>
                <el-table-column prop="address" label="地址"> </el-table-column>
                <el-table-column prop="outStart" label="期初应付"> </el-table-column>
                <el-table-column prop="outEnd" label="期末应付"> </el-table-column>
                <el-table-column prop="remark" label="备注"> </el-table-column>
                <el-table-column align="center" label="操作" :width="50">
                    <template v-slot="{row}">
                        <el-button size="small" @click="onRemoveUpdateSelection(row)" type="text">
                            移除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <span slot="footer" class="dialog-footer">
                <el-button :disabled="isMultipleLoading" @click="multipleDeleteVisible = false">取 消</el-button>
                <el-button
                    :loading="isMultipleLoading"
                    type="primary"
                    @click="onClickMultipleOkDelete(multipleSelection)"
                    >确 定</el-button
                >
            </span>
        </TheElDialog>
    </LayoutWrap>
</template>
<script>
import {mapGetters} from 'vuex';
import {getApiList, postApisList, putApisList, deleteApiById, deleteApiByIds} from '@/api/customer';
import FunctionDialog, {RULES} from '@/views/system/customer/FunctionDialog';
import {THE_MOMENT_YYYYMMDD_HHMMSS} from '@/utils/constant';
import {deepCopy} from '@/utils/utils';
import {v4 as uuidv4} from 'uuid';
import BatchDialog from '@/views/system/customer/BatchDialog';
import getRules from '@/views/system/customer/getRules';

const dataSourceDefault = {
    id: undefined,
    name: '',
    contact: '',
    phone: '',
    address: '',
    outStart: '',
    outEnd: '',
    remark: ''
};

export default {
    name: 'customer',
    components: {
        FunctionDialog,
        BatchDialog
    },
    data() {
        return {
            uuidv4,
            THE_MOMENT_YYYYMMDD_HHMMSS,
            formSearch: {
                keyName: 'name',
                keyValue: '',
                pageSize: 10,
                page: 1,
                count: 0
            },
            keyOptions: [
                {label: '名称', value: 'name', disabled: false},
                {label: '联系人', value: 'contact', disabled: false},
                {label: '联系电话', value: 'phone', disabled: false},
                {label: '地址', value: 'address', disabled: false},
                {label: '备注', value: 'remark', disabled: false}
            ],
            tableData: [],
            isLoading: false,
            dataSourceDefault,
            dataSourceDetail: {...dataSourceDefault},
            visibleDetail: false,
            title: '添加',
            dialogVisible: false,
            dialogLoading: false,
            multipleSelection: [],
            multipleValueSelection: [],
            multipleDeleteVisible: false, // 批量删除打开、关闭
            multipleDetailVisible: false,
            isMultipleLoading: false,
            multipleUpdateVisible: false,
            multipleAddVisible: false,
            multipleCreateSelection: [
                {...dataSourceDefault, uuid: uuidv4()},
                {...dataSourceDefault, uuid: uuidv4()}
            ],
            RULES: getRules()
        };
    },
    computed: {
        ...mapGetters({
            isMobile: 'app/isMobile'
        }),
        isMultSelect() {
            return this.multipleSelection.length > 0;
        }
    },
    created() {
        this.getList();
    },
    methods: {
        indexMethod(index) {
            return index + 1 + (this.formSearch.page - 1) * this.formSearch.pageSize;
        },
        onRemoveAddSelection(row) {
            this.multipleCreateSelection = this.multipleCreateSelection.filter(({uuid}) => uuid !== row.uuid);
        },
        onRemoveUpdateSelection(row) {
            this.multipleSelection = this.multipleSelection.filter(({uuid}) => uuid !== row.uuid);
            this.multipleValueSelection = this.multipleValueSelection.filter(({uuid}) => uuid !== row.uuid);
            const tRow = this.tableData.find(item => row._id && item._id === row._id);
            tRow && this.$refs.multipleUpdateTable.toggleRowSelection(tRow, false);
        },
        onPushSelection() {
            this.multipleCreateSelection.push({...dataSourceDefault, uuid: uuidv4()});
        },
        onChangePage(value) {
            this.formSearch = {...this.formSearch, ...value};
            this.getList();
        },
        resetForm(formSearch) {
            // this.$refs[formSearch].resetFields();
            const {keyName, keyValue, page, pageSize} = this.$options.data().formSearch;
            this.formSearch = {...this.formSearch, keyName, keyValue, page, pageSize};
        },
        handleSelectionChange(value) {
            this.multipleValueSelection = value;
            this.multipleSelection = deepCopy(value).map(item => {
                item.uuid = uuidv4();
                return item;
            });
        },
        // 批量删除
        onClickMultipleOkDelete(multipleSelection) {
            this.isMultipleLoading = true;
            deleteApiByIds(multipleSelection.map(item => item._id))
                .then(res => {
                    this.getList();
                })
                .catch(error => {
                    this.$message({showClose: true, type: 'error', message: '批量删除失败'});
                    console.error(error);
                })
                .finally(() => {
                    this.isMultipleLoading = false;
                    this.multipleDeleteVisible = false;
                });
        },
        async formValidates(values) {
            const handers = [];
            values.forEach(item => {
                const uuid = item.uuid;
                const formNames = [
                    `form_name_${uuid}`,
                    `form_contact_${uuid}`,
                    `form_phone_${uuid}`,
                    `form_address_${uuid}`,
                    `form_outStart_${uuid}`,
                    `form_outEnd_${uuid}`,
                    `form_remark_${uuid}`
                ];
                formNames.forEach(formName => {
                    if (!this.$refs[formName]) {
                        console.warn('formName', formName);
                        return;
                    }
                    const hander = new Promise((resolve, reject) => {
                        this.$refs[formName].validate((valid, fields) => {
                            if (valid) {
                                resolve(valid);
                                return;
                            }
                            reject(valid);
                        });
                    });
                    handers.push(hander);
                });
            });
            await Promise.all(handers);
        },
        // 批量添加
        async onClickMultipleOkCreate(multipleCreateSelection) {
            if (multipleCreateSelection.length === 0) {
                this.$message({showClose: true, type: 'error', message: '数据为空，批量添加失败'});
                return;
            }
            try {
                await this.formValidates(multipleCreateSelection);

                this.isMultipleLoading = true;
                postApisList(multipleCreateSelection)
                    .then(res => {
                        this.getList();
                        this.multipleAddVisible = false;
                        this.$message({showClose: true, type: 'success', message: '批量添加成功'});
                    })
                    .catch(error => {
                        const data = error.response && error.response.data;

                        if (data && data.error) {
                            this.$message({showClose: true, type: 'error', message: data.error});
                        } else {
                            this.$message({showClose: true, type: 'error', message: '批量添加失败'});
                        }
                        console.log(error);
                    })
                    .finally(() => {
                        this.isMultipleLoading = false;
                    });
            } catch (error) {
                console.warn('表单的校验失败');
                this.$message({showClose: true, type: 'warn', message: '表单的校验失败'});
            }
        },
        // 批量修改
        async onClickMultipleOkUpdate(multipleSelection) {
            if (multipleSelection.length === 0) {
                this.$message({showClose: true, type: 'error', message: '数据为空，批量修改失败'});
                return;
            }
            try {
                await this.formValidates(multipleSelection);
                this.isMultipleLoading = true;
                putApisList(multipleSelection)
                    .then(res => {
                        this.getList();
                        this.multipleUpdateVisible = false;
                        this.$message({showClose: true, type: 'success', message: '批量修改成功'});
                    })
                    .catch(error => {
                        const data = error.response && error.response.data;
                        if (data && data.error) {
                            this.$message({showClose: true, type: 'error', message: data.error});
                        } else {
                            this.$message({showClose: true, type: 'error', message: '批量修改失败'});
                        }
                        console.error(error);
                    })
                    .finally(() => {
                        this.isMultipleLoading = false;
                    });
            } catch (error) {
                console.warn('表单的校验失败');
                this.$message({showClose: true, type: 'warn', message: '表单的校验失败'});
            }
        },
        // 获取列表数据
        getList() {
            this.isLoading = true;
            const {keyName, keyValue, pageSize, page} = this.formSearch;
            const newItem = {pageSize, page, isDeleted: false};
            if (keyValue) {
                newItem[keyName] = keyValue;
            }
            getApiList(newItem)
                .then(({data: res}) => {
                    if (res.status === 200) {
                        const {data, count, page, pageSize} = res;
                        this.tableData = data;
                        this.formSearch = {...this.formSearch, page, pageSize, count};
                    }
                })
                .catch(error => {
                    console.log(error);
                })
                .finally(() => (this.isLoading = false));
        },

        onClickDetail(row, title) {
            this.title = title;
            this.visibleDetail = true;
            this.dataSourceDetail = {...row};
        },
        onClickDelete(row) {
            this.dialogVisible = true;
            this.dataSourceDetail = {...row};
        },
        onClickOkDelete(row) {
            this.dialogLoading = true;
            deleteApiById(row._id)
                .then(res => {
                    this.dialogVisible = false;
                    this.$message({showClose: true, type: 'success', message: '删除成功'});
                    this.getList();
                    this.dialogLoading = false;
                })
                .catch(err => {
                    this.$message({showClose: true, type: 'error', message: '删除失败'});
                    console.log('err :', err);
                    this.dialogVisible = false;
                    this.dialogLoading = false;
                });
        }
    }
};
</script>

<style lang="scss" scoped></style>
